var stopFlag = false;
/**
 * 开始抓取 的点击事件
 */
startSpider.addEventListener("click", async () => {
    let [tab] = await chrome.tabs.query({active: true, currentWindow: true});
    let optUser = $('#optUser').val()
    for (let i = 0; i < 1000000; i++) {
        if(stopFlag){
            console.log("停止了")
            break;
        }
        await waitTime(2000)
        chrome.scripting.executeScript(
            {
                target: {tabId: tab.id},
                function: startSpiderInject,
                args: [optUser]
            }
        );
    }
});

/**
 * 把方法注入到页面
 * @param {*} optUser 
 */
function startSpiderInject(optUser) {
    document.getElementsByClassName("a-last")[0].getElementsByTagName('a')[0].click();
    let commentDivArr = document.getElementsByClassName("a-section review aok-relative");
    let commentPage = []
    for (let i = 0; i < commentDivArr.length; i++) {
        let custName = commentDivArr[i].getElementsByClassName("a-profile-name")[0].innerText;
        let star = commentDivArr[i].getElementsByClassName("a-icon-alt")[0].innerText;
        let comment = commentDivArr[i].getElementsByClassName("a-size-base review-text review-text-content")[0].getElementsByTagName('span')[0].innerText;

        commentPage.push({
            custName,
            star,
            comment,
            optUser
        })
    }
    chrome.runtime.sendMessage({commentPage: commentPage}, function (response) {
        console.log('收到发送数据库回复');
    });

    if(!document.getElementsByClassName("a-disabled a-last")){
        chrome.runtime.sendMessage({"nextPageFlag": "1"}, function (response) {
            console.log('停止爬');
        });
    }
}


/**
 * 监听来自content-script的消息  也就是web页面
 */
chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
    console.log(request);
    console.log(sendResponse);
    console.log(sender);

    let parse = JSON.parse(JSON.stringify(request));
    if(parse.nextPageFlag){
        stopFlag = true;
    }else {
        let data = {
            comment: JSON.stringify(request),
            url: sender.url
        };
        $.ajax({
            type: 'POST',
            url: "http://127.0.0.1:8091/report/amazon/saveReviews",
            contentType: "application/json",
            data: JSON.stringify(data),
            success: function (data) {

            },
            dataType: "json"
        });
    }
    sendResponse('我是后台，我已收到你的消息：' + JSON.stringify(request));
});

/**
 * 等待函数  单位毫秒
 * @param time
 * @returns {Promise<unknown>}
 */
async function waitTime(time) {
    return new Promise(function (resolve) {
        setTimeout(resolve, time);
    });
}
